package com.ruoyi.yys.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.yys.common.enums.ErrorStatus;
import com.ruoyi.yys.domain.ImportExportTask;
import com.ruoyi.yys.domain.entityBo.ImportExportParamBo;
import com.ruoyi.yys.service.IImportExportTaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 导入导出任务Controller
 * 
 * @author xinyin
 * @date 2022-12-07
 */
@RestController
@RequestMapping("/importExport/task")
@RequiredArgsConstructor
@Api(tags = "导入导出任务管理")
public class ImportExportTaskController extends BaseController
{
    private final IImportExportTaskService importExportTaskService;

    /**
     * 查询导入导出任务列表
     */
    //@PreAuthorize("@ss.hasPermi('importExport:task:list')")
    @ApiOperation("获取导入导出任务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "system", value = "系统", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "createBy", value = "创建人", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "status", value = "任务状态（-3=主动终止,-2=超时,-1=异常,0=等待执行,1=执行中,2=执行完成）", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "status", value = "操作类型（import=导入,export=导出）", dataType = "Integer", dataTypeClass = Integer.class)
    })
    @GetMapping("/list")
    public TableDataInfo list(ImportExportTask importExportTask)
    {
        startPage();
        List<ImportExportTask> list = importExportTaskService.selectImportExportTaskList(importExportTask);
        return getDataTable(list);
    }

    /**
     * 导出导入导出任务列表
     */
    @PreAuthorize("@ss.hasPermi('importExport:task:export')")
    @Log(title = "导入导出任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ImportExportTask importExportTask)
    {
        List<ImportExportTask> list = importExportTaskService.selectImportExportTaskList(importExportTask);
        ExcelUtil<ImportExportTask> util = new ExcelUtil<ImportExportTask>(ImportExportTask.class);
        util.exportExcel(response, list, "导入导出任务数据");
    }

    /**
     * 获取导入导出任务详细信息
     */
    //@PreAuthorize("@ss.hasPermi('importExport:task:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取导入导出任务详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务id", dataType = "String", dataTypeClass = String.class)
    })
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(importExportTaskService.selectImportExportTaskById(id));
    }

    /**
     * 新增导入导出任务
     */
    @PreAuthorize("@ss.hasPermi('importExport:task:add')")
    @Log(title = "导入导出任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ImportExportTask importExportTask)
    {
        return toAjax(importExportTaskService.insertImportExportTask(importExportTask));
    }

    /**
     * 修改导入导出任务
     */
    @PreAuthorize("@ss.hasPermi('importExport:task:edit')")
    @Log(title = "导入导出任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ImportExportTask importExportTask)
    {
        return toAjax(importExportTaskService.updateImportExportTask(importExportTask));
    }

    /**
     * 删除导入导出任务
     */
//    @PreAuthorize("@ss.hasPermi('importExport:task:remove')")
    @Log(title = "导入导出任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(importExportTaskService.deleteImportExportTaskByIds(ids));
    }

    /**
     * 导出文件，并将操作记录入库
     *
     * @param importExportParamBo 进出口参数波
     */
    @ApiOperation("根据模板id导出任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sql", value = "sql", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "templateId", value = "模板id", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "createBy", value = "创建人", dataType = "String", dataTypeClass = String.class)
    })
    @PostMapping ("/exportByTempleId")
    public R exportByTempId(@RequestBody ImportExportParamBo importExportParamBo) {
        return R.ok(importExportTaskService.exportByTempId(importExportParamBo));
    }

    /**
     * 根据任务id 下载已完成好的文件
     *
     * @param id       id
     * @param fileName 设置下载后的文件名称
     * @param response 响应
     * @return {@link R}
     */
    @ApiOperation("根据任务id 下载已完成好的文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "fileName", value = "文件名称（下载到客户端后的重命名）", dataType = "String", dataTypeClass = String.class)
    })
    @PostMapping("/downlodaFileById")
    public R downlodaFileById(String id,String fileName, HttpServletResponse response) {
        return importExportTaskService.downlodaFileById(id,fileName,response);
    }

    /**
     * 根据任务id 下载已完成好的文件
     *
     * @param id       id
     * @param fileName 设置下载后的文件名称
     * @param response 响应
     * @return {@link R}
     */
    @ApiOperation("根据任务id 下载已完成好的文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "fileName", value = "文件名称（下载到客户端后的重命名）", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping("/downlodaFile")
    public R downlodaFile(String id,String fileName, HttpServletResponse response) {
        return importExportTaskService.downlodaFileById(id,fileName,response);
    }

    /**
     * 重新开始任务 根据任务id
     *
     * @param id id
     * @return {@link R}
     */
    @ApiOperation("重新开始任务 根据任务id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务id", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping("/restartTaskById")
    public R restartTaskById(String id) {
        try {
            importExportTaskService.restartTaskById(id);
            return R.ok();
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 停止任务 根据任务id
     *
     * @param id id
     * @return {@link R}
     */
    @ApiOperation("停止任务 根据任务id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务id", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping("/stopTaskById")
    public R stopTaskById(String id) {
        int update = importExportTaskService.updateTaskStatus(id, ErrorStatus.ACTIVEOVER.getCode(),null);
        return R.ok(update);
    }
}
